package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.leyou.auth.constant.JwtConstants.*;
import static com.leyou.auth.constant.RedisConstants.JTI_KEY_PREFIX;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     *
     * @param username 用户名
     * @param password 密码
     * @param response 响应
     * @return
     */
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        UserDTO userDTO = null;
        try {
            // 根据用户名以及密码，查找用户
            userDTO = userClient.queryUserByNameAndPass(username, password);
            // 用户为空，查找不到，报错
            if (null == userDTO) {
                throw new LyException(400, "请求有误");
            }
            // userDTO转换成UserDetail
            UserDetail userDetail = BeanHelper.copyProperties(userDTO, UserDetail.class);
            // 生成token
            String token = jwtUtils.createJwt(userDetail);
            // 创建cookie
            createCookie(response, token, -1);
        } catch (FeignException e) {
            // 把远程调用异常转换抛出
            throw new LyException(e.status(), e.getMessage());
        }

    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 删除redis
            String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
            Payload payload = jwtUtils.parseJwt(jwt);
            redisTemplate.delete(JTI_KEY_PREFIX + payload.getUserDetail().getId());
        } catch (Exception e) {
        }
        createCookie(response, "", 0);
    }

    /**
     * 生成cookie并返回
     * @param response 响应
     * @param token 生成的token
     */
    private void createCookie(HttpServletResponse response, String token, int age) {
        // 新建一个指定名称的cookie，值是token
        Cookie cookie = new Cookie(COOKIE_NAME, token);
        // cookie的作用域
        cookie.setDomain(DOMAIN);
        // 禁止JS操作cookie
        cookie.setHttpOnly(true);
        // cookie的有效期，-1就是跟随当前会话，0就是马上删除
        cookie.setMaxAge(age);
        // cookie的作用路径，/代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
